From ecc369d2efecb798b5f98df57a0937bd7b1eb577 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 27 Oct 2024 10:12:51 +0800 Subject: [PATCH] 20241027 finished. --- src/problem/mod.rs | 2 + src/problem/p684_redundant_connection.rs | 79 ++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 src/problem/p684_redundant_connection.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index dd6d8be..757f29a 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -278,3 +278,5 @@ mod p997_find_the_town_judge; mod p3180_maximum_total_reward_using_operations_i; mod p3181_maximum_total_reward_using_operations_ii; + +mod p684_redundant_connection; diff --git a/src/problem/p684_redundant_connection.rs b/src/problem/p684_redundant_connection.rs new file mode 100644 index 0000000..5dc2805 --- /dev/null +++ b/src/problem/p684_redundant_connection.rs @@ -0,0 +1,79 @@ +/** + * [684] Redundant Connection + */ +pub struct Solution {} + +// submission codes start here + +struct UnionFindSet { + parents: Vec, +} + +impl UnionFindSet { + fn new(n: usize) -> Self { + Self { + parents: (0..=n).collect(), + } + } + + fn find(&mut self, n: usize) -> usize { + if self.parents[n] == n { + n + } else { + self.parents[n] = self.find(self.parents[n]); + + self.parents[n] + } + } + + fn merge(&mut self, a: usize, b: usize) { + let (a, b) = (self.find(a), self.find(b)); + + self.parents[a] = b; + } +} + +impl Solution { + pub fn find_redundant_connection(edges: Vec>) -> Vec { + let n = edges.len(); + let mut set = UnionFindSet::new(n + 1); + + let mut result = None; + for edge in edges.iter() { + let (a, b) = (edge[0] as usize, edge[1] as usize); + + if set.find(a) == set.find(b) { + result = Some(vec![a as i32, b as i32]); + } + + set.merge(a, b); + } + + result.unwrap() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_684() { + assert_eq!( + vec![2, 3], + Solution::find_redundant_connection(vec![vec![1, 2], vec![1, 3], vec![2, 3]]) + ); + assert_eq!( + vec![1, 4], + Solution::find_redundant_connection(vec![ + vec![1, 2], + vec![2, 3], + vec![3, 4], + vec![1, 4], + vec![1, 5] + ]) + ); + } +}