DFS C++解Leetcode 1376 Time Needed to Inform All Employees 一家公司的每個員工都有一個獨特的ID,從0到n-1。負責人是headID的那位, manager[headID] = -1。manager[i]表示員工i的直接經理,員工i需要花費informTime[i]分鐘來通知他的直接下屬,通知所有員工所需的時間?
[LeetCode程式]https://www.youtube.com/watch?v=--vVXnaKPqI&list=PLYRlUBnWnd5IdDHk2BjqXwesydU17z_xk
====
A company's employee structure, each employee has a unique ID, from 0 to n-1. The head of the company is the one with the headID. manager[i] indicates the direct manager of employee i, manager[headID] = -1. Employee i takes informTime[i] minutes to inform his direct reports, how long does it take to inform all employees about the news?
- class Solution {
- public:
- vector<vector<int>> adj;
- // Adjacency list to represent the organizational hierarchy
- // Function to initialize the adjacency list
- void adj_ini(int n, vector<int>& manager){
- adj.resize(n);
- // Resize the adjacency list to accommodate 'n' vertices
- for(int i = 0; i < n; i++){
- int x = manager[i];//manager 'x' is the parent node
- if (x != -1) //i!=headID is special
- adj[x].push_back(i);
- // Add 'i' as a direct report of manager 'x'
- }
- }
- int timeNeed = 0; // Variable to store the maximum time needed to inform all employees
- // Depth-First Search (DFS) to calculate the maximum time needed
- void dfs(int i, int time, vector<int>& informTime){
- timeNeed = max(timeNeed, time); // Update the maximum time needed
- for(auto v: adj[i])
- dfs(v, time + informTime[i], informTime);
- // Recursive call for each direct report of employee 'i'
- }
- // Function to calculate the total time needed to inform all employees
- int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime){
- adj_ini(n, manager); // Initialize the adjacency list
- dfs(headID, 0, informTime);
- // Perform DFS starting from the headID (tree root)
- return timeNeed; // Return the maximum time needed
- }
- };
沒有留言:
張貼留言