diff --git a/src/lib.rs b/src/lib.rs index 91e9412c..4761fd83 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1750,6 +1750,7 @@ pub mod problem_2352_equal_row_and_column_pairs; pub mod problem_2353_design_a_food_rating_system; pub mod problem_2357_make_array_zero_by_subtracting_equal_amounts; pub mod problem_2358_maximum_number_of_groups_entering_a_competition; +pub mod problem_2360_longest_cycle_in_a_graph; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2360_longest_cycle_in_a_graph/iterative.rs b/src/problem_2360_longest_cycle_in_a_graph/iterative.rs new file mode 100644 index 00000000..5b7256fd --- /dev/null +++ b/src/problem_2360_longest_cycle_in_a_graph/iterative.rs @@ -0,0 +1,67 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +use std::mem; + +impl Solution { + pub fn longest_cycle(edges: Vec) -> i32 { + const MAX_BIT: u32 = 1 << 31; + + let mut edges = edges; + let n = edges.len(); + let mut result = 0; + let mut current_id = MAX_BIT - 1; + + for i in 0..n { + let mut state = &mut edges[i]; + + if ((*state + 1) as u32) < MAX_BIT { + current_id += 1; + + let start_id = current_id; + + loop { + let next = mem::replace(state, current_id as _) as usize; + + if let Some(next_state) = edges.get_mut(next) { + if ((*next_state + 1) as u32) < MAX_BIT { + state = next_state; + current_id += 1; + + continue; + } + + if *next_state as u32 >= start_id { + result = result.max(current_id - *next_state as u32); + } + } + + break; + } + } + } + + if result == 0 { + -1 + } else { + (result + 1) as _ + } + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn longest_cycle(edges: Vec) -> i32 { + Self::longest_cycle(edges) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2360_longest_cycle_in_a_graph/mod.rs b/src/problem_2360_longest_cycle_in_a_graph/mod.rs new file mode 100644 index 00000000..274cac0a --- /dev/null +++ b/src/problem_2360_longest_cycle_in_a_graph/mod.rs @@ -0,0 +1,23 @@ +pub mod iterative; + +pub trait Solution { + fn longest_cycle(edges: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&[3, 3, 4, 2, 3] as &[_], 3), + (&[2, -1, 3, 1], -1), + (&[3, 3, 4, 2, 3], 3), + (&[4, 3, 3, 4, 7, 2, 3, 3], 3), + ]; + + for (edges, expected) in test_cases { + assert_eq!(S::longest_cycle(edges.to_vec()), expected); + } + } +}