forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
66 lines (51 loc) · 1.35 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/// Source : https://leetcode.com/problems/employee-importance/description/
/// Author : liuyubobobo
/// Time : 2017-11-27
#include <iostream>
#include <vector>
#include <map>
using namespace std;
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
Employee(int id, int importance, vector<int> subordinates):
id(id), importance(importance), subordinates(subordinates){
}
};
/// DFS
/// Time Complexity: O(n)
/// Space Complexity: O(n)
class Solution {
private:
map<int, Employee*> record;
public:
int getImportance(vector<Employee*> employees, int id) {
record.clear();
for(Employee* employee: employees)
record[employee->id] = employee;
return dfs(id);
}
private:
int dfs(int id){
int res = record[id]->importance;
for(int sid: record[id]->subordinates)
res += dfs(sid);
return res;
}
};
int main() {
vector<Employee*> vec = {
new Employee(1, 5, {2, 3}),
new Employee(2, 3, vector<int>()),
new Employee(3, 3, vector<int>())
};
cout << Solution().getImportance(vec, 1) << endl;
return 0;
}