20250329 finished.
This commit is contained in:
parent
7fd29c8f96
commit
0b20b8fa9c
|
@ -566,3 +566,5 @@ mod p2829_determine_the_minimum_sum_of_a_k_avoiding_array;
|
|||
mod p2712_minimum_cost_to_make_all_characters_equal;
|
||||
|
||||
mod p2716_minimize_string_length;
|
||||
|
||||
mod p2360_longest_cycle_in_a_graph;
|
||||
|
|
55
src/problem/p2360_longest_cycle_in_a_graph.rs
Normal file
55
src/problem/p2360_longest_cycle_in_a_graph.rs
Normal file
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
* [2360] Longest Cycle in a Graph
|
||||
*/
|
||||
pub struct Solution {}
|
||||
|
||||
// submission codes start here
|
||||
|
||||
impl Solution {
|
||||
pub fn longest_cycle(edges: Vec<i32>) -> i32 {
|
||||
let n = edges.len();
|
||||
let mut labels = vec![0; n];
|
||||
|
||||
let mut current_label = 0;
|
||||
let mut result = -1;
|
||||
|
||||
for i in 0..n {
|
||||
if labels[i] != 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut pos = i as i32;
|
||||
let start_label = current_label;
|
||||
|
||||
while pos != -1 {
|
||||
current_label += 1;
|
||||
// 遇到已经遍历过的节点
|
||||
let real_pos = pos as usize;
|
||||
if labels[real_pos] != 0 {
|
||||
if labels[real_pos] > start_label {
|
||||
result = result.max(current_label - labels[real_pos]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
labels[real_pos] = current_label;
|
||||
pos = edges[real_pos];
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
// submission codes end
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_2360() {
|
||||
assert_eq!(3, Solution::longest_cycle(vec![3, 3, 4, 2, 3]));
|
||||
assert_eq!(-1, Solution::longest_cycle(vec![2, -1, 3, 1]));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user