herrDeng網內搜尋

自訂搜尋

Ads

2023年6月3日 星期六

DFS C++解Leetcode 1376 Time Needed to Inform All Employees(C++ code)


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?
  1. class Solution {
  2. public:
  3. vector<vector<int>> adj;
  4. // Adjacency list to represent the organizational hierarchy
  5.  
  6. // Function to initialize the adjacency list
  7. void adj_ini(int n, vector<int>& manager){
  8. adj.resize(n);
  9. // Resize the adjacency list to accommodate 'n' vertices
  10.  
  11. for(int i = 0; i < n; i++){
  12. int x = manager[i];//manager 'x' is the parent node
  13. if (x != -1) //i!=headID is special
  14. adj[x].push_back(i);
  15. // Add 'i' as a direct report of manager 'x'
  16. }
  17. }
  18.  
  19. int timeNeed = 0; // Variable to store the maximum time needed to inform all employees
  20.  
  21. // Depth-First Search (DFS) to calculate the maximum time needed
  22. void dfs(int i, int time, vector<int>& informTime){
  23. timeNeed = max(timeNeed, time); // Update the maximum time needed
  24. for(auto v: adj[i])
  25. dfs(v, time + informTime[i], informTime);
  26. // Recursive call for each direct report of employee 'i'
  27. }
  28.  
  29. // Function to calculate the total time needed to inform all employees
  30. int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime){
  31. adj_ini(n, manager); // Initialize the adjacency list
  32. dfs(headID, 0, informTime);
  33. // Perform DFS starting from the headID (tree root)
  34.  
  35. return timeNeed; // Return the maximum time needed
  36. }
  37. };
  38.  

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章