Advertisement
nikunjsoni

851

Apr 30th, 2021
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {
  4.         int n = quiet.size();
  5.         vector<vector<int>> graph(n);
  6.        
  7.         for(auto edge: richer)
  8.             graph[edge[1]].push_back(edge[0]);
  9.        
  10.         vector<int> ans(n, -1);
  11.         for(int i=0; i<n; i++){
  12.             if(ans[i] == -1)
  13.                 dfs(i, graph, quiet, ans);
  14.         }
  15.         return ans;
  16.     }
  17.    
  18.     int dfs(int node, vector<vector<int>> &graph, vector<int>& quiet, vector<int> &ans){
  19.         if(ans[node] != -1) return (quiet[ans[node]] < quiet[node]) ? ans[node] : node;
  20.         int res = node;
  21.         for(auto child: graph[node]){
  22.             int subtreeSmall = dfs(child, graph, quiet, ans);
  23.             if(quiet[res] > quiet[subtreeSmall])
  24.                 res = subtreeSmall;
  25.         }
  26.         return ans[node] = res;
  27.     }
  28.    
  29. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement