/* Given a data structure that saves employee information, it contains the employee’s unique id, importance? and the id of the immediate subordinates.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. Their corresponding importance is 15, 10, 5.
Then the data structure of employee 1 is [1, 15, [2]], the data structure of employee 2 is [2, 10, [3]], and the data structure of employee 3 is [3, 5, []].
Note that although employee 3 is also a subordinate of employee 1, because it is not a direct subordinate, it is not reflected in the data structure of employee 1.
Now enter all employee information of a company and a single employee id to return the sum of the importance of this employee and all his subordinates.
Source: LeetCode
Link: https://leetcode-cn.com/problems/employee-importance
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source. */
/*Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1’s own importance is 5 , He has two direct subordinates 2 and 3, and the importance of 2 and 3 are both 3. Therefore, the total importance of employee 1 is 5 + 3 + 3 = 11.
Source: LeetCode
Link: https://leetcode-cn.com/problems/employee-importance
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate/*
/*
// Definition for Employee.
class Employee {
public:
int id;
int importance;
vector<int> subordinates;
};
*/
class Solution {
public:
void Dfs(int id, unordered_map<int, Employee*>& info, int& sum) {
sum += info[id]->importance;
//直系下属为空即是结束条件
for (const auto& e : info[id]->subordinates) {
Dfs(e, info, sum);
}
}
int getImportance(vector<Employee*> employees, int id) {
if (employees.size() == 0)
return 0;
//保存员工id,和他对应的信息的映射,方便遍历
unordered_map<int, Employee*> um;
for (const auto& e : employees) {
um[e->id] = e;
}
//重要度之和
int sum = 0;
//从id员工开始深度遍历,直到一个员工的直系下属为空
Dfs(id, um, sum);
return sum;
}
};