forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loud-and-rich.cpp
33 lines (31 loc) · 1003 Bytes
/
loud-and-rich.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
// Time: O(q + r)
// Space: O(q + r)
class Solution {
public:
vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
vector<vector<int>> graph(quiet.size());
for (const auto& r : richer) {
graph[r[1]].emplace_back(r[0]);
}
vector<int> result(quiet.size(), -1);
for (int i = 0; i < quiet.size(); ++i) {
dfs(graph, quiet, i, &result);
}
return result;
}
private:
int dfs(const vector<vector<int>>& graph,
const vector<int>& quiet,
int node, vector<int> *result) {
if ((*result)[node] == -1) {
(*result)[node] = node;
for (const auto& nei : graph[node]) {
int smallest_person = dfs(graph, quiet, nei, result);
if (quiet[smallest_person] < quiet[(*result)[node]]) {
(*result)[node] = smallest_person;
}
}
}
return (*result)[node];
}
};