Skip to content

Commit

Permalink
Add problem 2360: Longest Cycle in a Graph
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 13, 2024
1 parent e0fbca7 commit 317fb9a
Show file tree
Hide file tree
Showing 3 changed files with 91 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
67 changes: 67 additions & 0 deletions src/problem_2360_longest_cycle_in_a_graph/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::mem;

impl Solution {
pub fn longest_cycle(edges: Vec<i32>) -> 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>) -> i32 {
Self::longest_cycle(edges)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
23 changes: 23 additions & 0 deletions src/problem_2360_longest_cycle_in_a_graph/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
pub mod iterative;

pub trait Solution {
fn longest_cycle(edges: Vec<i32>) -> i32;
}

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

pub fn run<S: Solution>() {
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);
}
}
}

0 comments on commit 317fb9a

Please sign in to comment.