leetcode 851. Loud and Rich
Posted hopskin1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 851. Loud and Rich相关的知识,希望对你有一定的参考价值。
class Solution { int dfs(vector<int>&res,int i,vector<int>& quiet,map<int,vector<int>>& m){ if(res[i]>0) return res[i]; res[i]=i; for(int j=0;j<m[i].size();++j){ if(quiet[res[i]]>quiet[dfs(res,m[i][j],quiet,m)]) res[i]=res[m[i][j]]; } return res[i]; } public: vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) { map<int,vector<int>> m; for(auto& v: richer){ m[v[1]].push_back(v[0]); } vector<int> res=vector<int>(quiet.size(),-1); for(int i=0;i<quiet.size();++i){ dfs(res,i,quiet,m); } return res; } };
python代码
class Solution(object): def loudAndRich(self, richer, quiet): """ :type richer: List[List[int]] :type quiet: List[int] :rtype: List[int] """ m=collections.defaultdict(list) for i,j in richer: m[j].append(i) res=[-1]*len(quiet) def dfs(i): if res[i]>0: return res[i] res[i]=i for j in m[i]: if quiet[res[i]]>quiet[dfs(j)]: res[i]=res[j] return res[i] for i in range(len(res)): dfs(i) return res
以上是关于leetcode 851. Loud and Rich的主要内容,如果未能解决你的问题,请参考以下文章
851. Loud and Rich —— weekly contest 87
codeforces 851D Arpa and a list of numbers
Arpa and an exam about geometry(codeforces 851B)