結果

問題 No.2290 UnUnion Find
ユーザー haihamabossuhaihamabossu
提出日時 2023-05-05 22:45:56
言語 Rust
(1.77.0)
結果
AC  
実行時間 298 ms / 2,000 ms
コード長 7,773 bytes
コンパイル時間 5,971 ms
コンパイル使用メモリ 157,780 KB
実行使用メモリ 6,688 KB
最終ジャッジ日時 2023-08-15 05:37:12
合計ジャッジ時間 21,780 ms
ジャッジサーバーID
(参考情報)
judge12 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,384 KB
testcase_02 AC 295 ms
4,380 KB
testcase_03 AC 215 ms
4,380 KB
testcase_04 AC 212 ms
4,380 KB
testcase_05 AC 218 ms
4,380 KB
testcase_06 AC 212 ms
4,380 KB
testcase_07 AC 209 ms
4,380 KB
testcase_08 AC 218 ms
4,376 KB
testcase_09 AC 211 ms
4,376 KB
testcase_10 AC 212 ms
4,380 KB
testcase_11 AC 214 ms
4,380 KB
testcase_12 AC 216 ms
4,380 KB
testcase_13 AC 214 ms
4,380 KB
testcase_14 AC 215 ms
4,380 KB
testcase_15 AC 219 ms
4,380 KB
testcase_16 AC 210 ms
4,380 KB
testcase_17 AC 215 ms
4,380 KB
testcase_18 AC 215 ms
4,376 KB
testcase_19 AC 243 ms
4,520 KB
testcase_20 AC 268 ms
6,688 KB
testcase_21 AC 294 ms
4,376 KB
testcase_22 AC 258 ms
4,376 KB
testcase_23 AC 256 ms
4,376 KB
testcase_24 AC 251 ms
5,356 KB
testcase_25 AC 271 ms
4,376 KB
testcase_26 AC 257 ms
6,076 KB
testcase_27 AC 254 ms
5,552 KB
testcase_28 AC 246 ms
4,384 KB
testcase_29 AC 249 ms
5,024 KB
testcase_30 AC 298 ms
4,380 KB
testcase_31 AC 246 ms
4,832 KB
testcase_32 AC 270 ms
4,380 KB
testcase_33 AC 247 ms
4,376 KB
testcase_34 AC 274 ms
6,660 KB
testcase_35 AC 262 ms
6,076 KB
testcase_36 AC 265 ms
4,380 KB
testcase_37 AC 252 ms
4,380 KB
testcase_38 AC 269 ms
4,376 KB
testcase_39 AC 259 ms
4,376 KB
testcase_40 AC 252 ms
5,896 KB
testcase_41 AC 275 ms
4,380 KB
testcase_42 AC 242 ms
4,576 KB
testcase_43 AC 244 ms
4,380 KB
testcase_44 AC 215 ms
4,376 KB
testcase_45 AC 227 ms
4,380 KB
testcase_46 AC 237 ms
4,380 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

//https://github.com/rust-lang-ja/ac-library-rs

pub mod dsu {
    //! A Disjoint set union (DSU) with union by size and path compression.

    /// A Disjoint set union (DSU) with union by size and path compression.
    ///
    /// See: [Zvi Galil and Giuseppe F. Italiano, Data structures and algorithms for disjoint set union problems](https://core.ac.uk/download/pdf/161439519.pdf)
    ///
    /// In the following documentation, let $n$ be the size of the DSU.
    ///
    /// # Example
    ///
    /// ```
    /// use ac_library_rs::Dsu;
    /// use proconio::{input, source::once::OnceSource};
    ///
    /// input! {
    ///     from OnceSource::from(
    ///         "5\n\
    ///          3\n\
    ///          0 1\n\
    ///          2 3\n\
    ///          3 4\n",
    ///     ),
    ///     n: usize,
    ///     abs: [(usize, usize)],
    /// }
    ///
    /// let mut dsu = Dsu::new(n);
    /// for (a, b) in abs {
    ///     dsu.merge(a, b);
    /// }
    ///
    /// assert!(dsu.same(0, 1));
    /// assert!(!dsu.same(1, 2));
    /// assert!(dsu.same(2, 4));
    ///
    /// assert_eq!(
    ///     dsu.groups()
    ///         .into_iter()
    ///         .map(|mut group| {
    ///             group.sort_unstable();
    ///             group
    ///         })
    ///         .collect::<Vec<_>>(),
    ///     [&[0, 1][..], &[2, 3, 4][..]],
    /// );
    /// ```
    pub struct Dsu {
        n: usize,
        // root node: -1 * component size
        // otherwise: parent
        parent_or_size: Vec<i32>,
    }

    impl Dsu {
        /// Creates a new `Dsu`.
        ///
        /// # Constraints
        ///
        /// - $0 \leq n \leq 10^8$
        ///
        /// # Complexity
        ///
        /// - $O(n)$
        pub fn new(size: usize) -> Self {
            Self {
                n: size,
                parent_or_size: vec![-1; size],
            }
        }

        // `\textsc` does not work in KaTeX
        /// Performs the Uɴɪᴏɴ operation.
        ///
        /// # Constraints
        ///
        /// - $0 \leq a < n$
        /// - $0 \leq b < n$
        ///
        /// # Panics
        ///
        /// Panics if the above constraints are not satisfied.
        ///
        /// # Complexity
        ///
        /// - $O(\alpha(n))$ amortized
        pub fn merge(&mut self, a: usize, b: usize) -> usize {
            assert!(a < self.n);
            assert!(b < self.n);
            let (mut x, mut y) = (self.leader(a), self.leader(b));
            if x == y {
                return x;
            }
            if -self.parent_or_size[x] < -self.parent_or_size[y] {
                std::mem::swap(&mut x, &mut y);
            }
            self.parent_or_size[x] += self.parent_or_size[y];
            self.parent_or_size[y] = x as i32;
            x
        }

        /// Returns whether the vertices $a$ and $b$ are in the same connected component.
        ///
        /// # Constraints
        ///
        /// - $0 \leq a < n$
        /// - $0 \leq b < n$
        ///
        /// # Panics
        ///
        /// Panics if the above constraint is not satisfied.
        ///
        /// # Complexity
        ///
        /// - $O(\alpha(n))$ amortized
        pub fn same(&mut self, a: usize, b: usize) -> bool {
            assert!(a < self.n);
            assert!(b < self.n);
            self.leader(a) == self.leader(b)
        }

        /// Performs the Fɪɴᴅ operation.
        ///
        /// # Constraints
        ///
        /// - $0 \leq a < n$
        ///
        /// # Panics
        ///
        /// Panics if the above constraint is not satisfied.
        ///
        /// # Complexity
        ///
        /// - $O(\alpha(n))$ amortized
        pub fn leader(&mut self, a: usize) -> usize {
            assert!(a < self.n);
            if self.parent_or_size[a] < 0 {
                return a;
            }
            self.parent_or_size[a] = self.leader(self.parent_or_size[a] as usize) as i32;
            self.parent_or_size[a] as usize
        }

        /// Returns the size of the connected component that contains the vertex $a$.
        ///
        /// # Constraints
        ///
        /// - $0 \leq a < n$
        ///
        /// # Panics
        ///
        /// Panics if the above constraint is not satisfied.
        ///
        /// # Complexity
        ///
        /// - $O(\alpha(n))$ amortized
        pub fn size(&mut self, a: usize) -> usize {
            assert!(a < self.n);
            let x = self.leader(a);
            -self.parent_or_size[x] as usize
        }

        /// Divides the graph into connected components.
        ///
        /// The result may not be ordered.
        ///
        /// # Complexity
        ///
        /// - $O(n)$
        pub fn groups(&mut self) -> Vec<Vec<usize>> {
            let mut leader_buf = vec![0; self.n];
            let mut group_size = vec![0; self.n];
            for i in 0..self.n {
                leader_buf[i] = self.leader(i);
                group_size[leader_buf[i]] += 1;
            }
            let mut result = vec![Vec::new(); self.n];
            for i in 0..self.n {
                result[i].reserve(group_size[i]);
            }
            for i in 0..self.n {
                result[leader_buf[i]].push(i);
            }
            result
                .into_iter()
                .filter(|x| !x.is_empty())
                .collect::<Vec<Vec<usize>>>()
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn dsu_works() {
            let mut d = Dsu::new(4);
            d.merge(0, 1);
            assert!(d.same(0, 1));
            d.merge(1, 2);
            assert!(d.same(0, 2));
            assert_eq!(d.size(0), 3);
            assert!(!d.same(0, 3));
            assert_eq!(d.groups(), vec![vec![0, 1, 2], vec![3]]);
        }
    }
}
use dsu::*;

fn solve(scanner: &mut Scanner) {
    let n: usize = scanner.next();
    let q: usize = scanner.next();
    let mut leaders = std::collections::BTreeSet::new();
    for u in 0..n {
        leaders.insert(u);
    }
    let mut dsu = Dsu::new(n);
    for _ in 0..q {
        let t: usize = scanner.next();
        if t == 1 {
            let u: usize = scanner.next();
            let v: usize = scanner.next();
            let u = u - 1;
            let v = v - 1;
            let lu = dsu.leader(u);
            let lv = dsu.leader(v);
            dsu.merge(u, v);
            let l = dsu.leader(u);
            for &k in [lu, lv].iter() {
                if k != l {
                    leaders.remove(&k);
                }
            }
        } else {
            let v: usize = scanner.next();
            let v = v - 1;
            let lv = dsu.leader(v);
            let mut ans: isize = -1;
            for &l in leaders.iter() {
                if l != lv {
                    ans = (l + 1) as isize;
                    break;
                }
            }
            println!("{}", ans);
        }
    }
}

fn main() {
    let mut scanner = Scanner::new();
    let t: usize = 1;
    for _ in 0..t {
        solve(&mut scanner);
    }
}

pub struct Scanner {
    buf: Vec<String>,
}

impl Scanner {
    fn new() -> Self {
        Self { buf: vec![] }
    }

    fn next<T: std::str::FromStr>(&mut self) -> T {
        loop {
            if let Some(x) = self.buf.pop() {
                return x.parse().ok().expect("");
            }
            let mut source = String::new();
            std::io::stdin().read_line(&mut source).expect("");
            self.buf = Self::split(source);
        }
    }

    fn split(source: String) -> Vec<String> {
        source
            .split_whitespace()
            .rev()
            .map(String::from)
            .collect::<Vec<_>>()
    }
}
0