很重要的是,想到用二维数组,一维数组根本不好做: 相同的manager的都存到二维数组同一维对应的一维数组中,dfs遍历到leaf,找到最大值,都加起来.

C++:

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
vector<vector<int>> v;
vector<int> t;

class Solution {
public:
int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
v.clear();
v.resize(n);
t = informTime;
for (int i = 0; i < n; ++i) {
if (manager[i] != -1) {
v[manager[i]].push_back(i);
}
}
return dfs(headID);
}

int dfs(int m) {
int res = 0;
for (int i : v[m]) {
res = max(res, dfs(i));
}
return res + t[m];
}
};