From bf7033033a7e631a4ac6c4ba8d761e55d4ce2f04 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 17 Mar 2024 11:26:12 +0800 Subject: [PATCH] 20240317 Finished --- src/problem/mod.rs | 3 +- src/problem/p310_minimum_height_trees.rs | 83 ++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 src/problem/p310_minimum_height_trees.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 52a0729..71bdf72 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -75,4 +75,5 @@ mod p1261_find_elements_in_a_contaminated_binary_tree; mod p2864_maximum_odd_binary_number; mod p2789_largest_element_in_an_array_after_merge_operations; mod p2312_selling_pieces_of_wood; -mod p2684_maximum_number_of_moves_in_a_grid; \ No newline at end of file +mod p2684_maximum_number_of_moves_in_a_grid; +mod p310_minimum_height_trees; \ No newline at end of file diff --git a/src/problem/p310_minimum_height_trees.rs b/src/problem/p310_minimum_height_trees.rs new file mode 100644 index 0000000..d12a659 --- /dev/null +++ b/src/problem/p310_minimum_height_trees.rs @@ -0,0 +1,83 @@ +/** + * [310] Minimum Height Trees + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::VecDeque; + +impl Solution { + pub fn find_min_height_trees(n: i32, edges: Vec>) -> Vec { + let n = n as usize; + let mut graph = vec![vec![];n]; + + for edge in &edges { + let x = edge[0] as usize; + let y = edge[1] as usize; + + graph[x].push(y); + graph[y].push(x); + } + + let mut parents = vec![usize::MAX;n]; + let x = Solution::find_longest_node(0, &mut parents, &graph); + let mut y = Solution::find_longest_node(x, &mut parents, &graph); + + let mut path = Vec::new(); + parents[x] = usize::MAX; + + parents = dbg!(parents); + while y != usize::MAX { + path.push(y); + y = parents[y]; + } + + let length = path.len(); + + return if length % 2 != 0 { + vec![path[length / 2] as i32] + } else { + vec![path[length / 2 - 1] as i32, path[length / 2] as i32] + }; + } + + fn find_longest_node(node: usize, parents: &mut Vec, graph: &Vec>) -> usize { + let n = graph.len(); + + let mut queue = VecDeque::with_capacity(n); + let mut visited = vec![false;n]; + + queue.push_back(node); + visited[node] = true; + let mut result = usize::MAX; + + while !queue.is_empty() { + let now = queue.pop_front().unwrap(); + dbg!(now); + result = now; + for next in &graph[now] { + let next = *next; + if !visited[next] { + visited[next] = true; + parents[next] = now; + queue.push_back(next); + } + } + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_310() { + assert_eq!(vec![1], Solution::find_min_height_trees(4, vec![vec![1,0], vec![1,2], vec![1,3]])); + } +}