problems(rs): add “1376. Time Needed to Inform All Employees”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-06-03 22:36:46 +02:00
parent efeafcae88
commit e0f7ae0937
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,37 @@
use std::collections::{HashMap, HashSet, VecDeque};
impl Solution {
fn from_managers(managers: &[i32]) -> HashMap<usize, HashSet<usize>> {
let mut mapping = HashMap::new();
for (i, manager) in managers
.iter()
.enumerate()
.filter(|&(_, &manager)| manager != -1)
{
mapping
.entry(*manager as usize)
.or_insert_with(HashSet::new)
.insert(i);
}
mapping
}
pub fn num_of_minutes(_n: i32, head_id: i32, manager: Vec<i32>, inform_time: Vec<i32>) -> i32 {
let manager_mapping = Solution::from_managers(&manager);
let mut q = VecDeque::new();
q.push_back((head_id as usize, 0));
let mut minutes = -1;
while let Some((manager, t)) = q.pop_front() {
minutes = std::cmp::max(minutes, t);
for employee in manager_mapping.get(&manager).unwrap_or(&HashSet::new()) {
q.push_back((*employee, t + inform_time[manager]));
}
}
minutes
}
}