Skip to content

Commit

Permalink
Add problem 2316: Count Unreachable Pairs of Nodes in an Undirected G…
Browse files Browse the repository at this point in the history
…raph
  • Loading branch information
EFanZh committed Nov 9, 2024
1 parent 2436138 commit 0dbb0f3
Show file tree
Hide file tree
Showing 3 changed files with 92 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 @@ -1717,6 +1717,7 @@ pub mod problem_2305_fair_distribution_of_cookies;
pub mod problem_2309_greatest_english_letter_in_upper_and_lower_case;
pub mod problem_2310_sum_of_numbers_with_units_digit_k;
pub mod problem_2315_count_asterisks;
pub mod problem_2316_count_unreachable_pairs_of_nodes_in_an_undirected_graph;

#[cfg(test)]
mod test_utilities;
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
pub struct Solution;

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

use std::collections::VecDeque;

impl Solution {
pub fn count_pairs(n: i32, edges: Vec<Vec<i32>>) -> i64 {
let n = n as u32 as usize;
let mut nodes = vec![Vec::new(); n].into_boxed_slice();

for edge in edges {
let [from, to]: [_; 2] = edge.try_into().ok().unwrap();

nodes[from as u32 as usize].push(to as u32);
nodes[to as u32 as usize].push(from as u32);
}

let mut total_count = 0_u64;
let mut result = 0;
let mut visited = vec![false; n].into_boxed_slice();
let mut queue = VecDeque::new();

for mut node in 0..n {
if let state @ false = &mut visited[node] {
*state = true;

let mut count = 1;

loop {
for &next in &nodes[node] {
if let state @ false = &mut visited[next as usize] {
*state = true;

queue.push_back(next);
}
}

if let Some(next) = queue.pop_front() {
node = next as _;
count += 1;
} else {
break;
}
}

result += total_count * count;
total_count += count;
}
}

result as _
}
}

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

impl super::Solution for Solution {
fn count_pairs(n: i32, edges: Vec<Vec<i32>>) -> i64 {
Self::count_pairs(n, edges)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub mod bfs;

pub trait Solution {
fn count_pairs(n: i32, edges: Vec<Vec<i32>>) -> i64;
}

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

pub fn run<S: Solution>() {
let test_cases = [
((3, &[[0, 1], [0, 2], [1, 2]] as &[_]), 0),
((7, &[[0, 2], [0, 5], [2, 4], [1, 6], [5, 4]]), 14),
];

for ((n, edges), expected) in test_cases {
assert_eq!(S::count_pairs(n, edges.iter().map(Vec::from).collect()), expected);
}
}
}

0 comments on commit 0dbb0f3

Please sign in to comment.